package net.xyuu.web;

import java.util.Arrays;

import javax.validation.Valid;
import javax.validation.Validator;
import javax.validation.metadata.BeanDescriptor;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.security.provisioning.JdbcUserDetailsManager;
import org.springframework.security.provisioning.UserDetailsManager;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;

import net.xyuu.entity.User;
import net.xyuu.entity.UserRegisterForm;
import net.xyuu.repository.UserRepository;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.method.annotation.MvcUriComponentsBuilder;
import org.springframework.web.util.UriComponents;

@Controller
public class UserResource {

	@Autowired
	private UserRepository userRepository;
	@Autowired
	private Environment env;

	@PostMapping("/userRegister")
	public String post(@Valid UserRegisterForm userRegisterForm, BindingResult bindingResult) {
		if (bindingResult.hasErrors()) {
			return "register";
		}
		userRepository.save(userRegisterForm);
		return "redirect:/login";
	}

	@GetMapping("/login")
	public String login(Model model) {
		if (Arrays.binarySearch(env.getActiveProfiles(), "dev") >= 0) {
			model.addAttribute("email", "xyuu@xyuu.net");
			model.addAttribute("password", "password");
		}
		return "login";
	}

	@GetMapping("/")
	public String index() {
		
		//BeanDescriptor bean = validator.getConstraintsForClass(User.class);
		
		return "index";
	}

	@GetMapping("/register")
	public String register(UserRegisterForm userRegisterForm) {
		return "register";
	}
	
    @Autowired
    private Validator validator;
	
	@GetMapping("/userRegisterForm")
	public String user(){
		//userRepository.findAll();
		return "user";
	}

	@PostMapping("/password")
	public String password(JdbcUserDetailsManager userDetailsManager, String oldPassword, String newPassword) {
		userDetailsManager.changePassword(oldPassword, newPassword);
		return "register";
	}
}
